package study.ssm.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import study.ssm.entity.Product;
import study.ssm.service.ProductService;

import java.util.List;

@Controller
@RequiredArgsConstructor
@RequestMapping("/product")
public class ProductController {

    private final ProductService productService;

    @GetMapping("/create")
    public String create() {
        return "/product/create";
    }
    @GetMapping("/update")
    public String update(Integer id, Model model) {
        Product product = productService.getById(id);
        model.addAttribute("product", product);
        return "/product/update";
    }

    @PostMapping("/create")
    public String create(Product product) {
        productService.create(product);
        return "redirect:/product/list";
    }

    @GetMapping("/remove")
    public String remove( Integer id) {
        productService.removeById(id);
        return "redirect:/product/list";
    }

    @PostMapping("/update")
    public String update(Product product) {
        productService.update(product);
        return "redirect:/product/list";
    }

    @RequestMapping( "/list")
    public String list(Product product,Model model) {
        List<Product> list = productService.list(product);
        model.addAttribute("list", list);
        return "/product/index";
    }

    @GetMapping("/detail/{id}")
    public String detail(@PathVariable Integer id, Model model) {
        Product product = productService.getById(id);
        model.addAttribute("product", product);
        return "/product/detail";
    }
}
